package chapter3;

public class HeapSort {


    public static void heapInsert(int[] arr,int index){
        while (arr[index] > arr[(index-1)/2]){
            swap(arr,index,(index-1)/2);
            index = (index-1)/2;
        }
    }

    public static void heapify(int[] arr,int index,int heapSize){
        int left = 2*index +1;
        while (left < heapSize){//左孩子存在
            //找出孩子中的最大值
            int largest = left+1 < heapSize && arr[left]<arr[left+1]?left+1:left;
            //孩子最大值和父节点比较
            largest = arr[index]<arr[largest]?largest:index;
            if (largest == index){
                break;
            }
            swap(arr,index,largest);
            index = largest;
            left = 2*index +1;
        }
    }


    public static void  swap(int[] arr,int x,int y){
        int tmp = arr[x];
        arr[x] = arr[y];
        arr[y] = tmp;
    }

    public static void HeapSort(int[] arr){
        if (arr == null || arr.length <2){
            return;
        }
        for (int i = 0; i < arr.length; i++) {
            heapInsert(arr,i);
        }
        int heapSize = arr.length;
        swap(arr,0,--heapSize);
        while (heapSize >0){
            heapify(arr,0,heapSize);
            swap(arr,0,--heapSize);
        }
    }

    public static void main(String[] args) {

    }
}
